<template>
  <div ref="echartRef" class="echarts_container"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, ref, shallowRef, watch, defineProps, defineEmits } from 'vue'

// 定义 emits，用于向父组件传递点击事件
const emit = defineEmits(['barchartClick'])
const var_names = {
  gdp_total: '总GDP',
  gdp_1st: '第一产业',
  gdp_2nd: '第二产业',
  gdp_3rd: '第三产业'
}
// 定义props
const props = defineProps({
  labelFontsize: {
    type: Number,
    default: 16
  },
  titleName: {
    type: String,
    default: ''
  },
  barData: {
    type: Object,
    default: () => {}
  }
})
const echartRef = ref(null)
let chartInstance = shallowRef(null)

let theOption = {
  title: {
    text: props.titleName,
    textStyle:{
      color: '#ffffff'
    },
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    textStyle:{
      color: '#ffffff'
    },
    left: 'left'
  },
  series: [
    {
      name: 'GDP',
      type: 'pie',
      radius: '50%',
      data: [
        { value: props.barData.gdp_1st, name: var_names['gdp_1st'] },
        { value: props.barData.gdp_2nd, name: var_names['gdp_2nd'] },
        { value: props.barData.gdp_3rd, name: var_names['gdp_3rd'] }
      ],
    }
  ]
}
function handleChartClick(params){
  emit('barchartClick', params)
  // 获取点击的柱状图的索引
  let dataIndex = params.dataIndex
  // 取消所有柱的高亮
  chartInstance.value.dispatchAction({
    type: 'downplay',
    seriesIndex: 1
  })
  // 高亮点击的柱
  chartInstance.value.dispatchAction({
    type: 'highlight',
    dataIndex: dataIndex
  })
  
}
onMounted(() => {
  console.log('饼状图获得数据：', props);
  
  if (echartRef.value) {
    chartInstance.value = echarts.init(echartRef.value)
    chartInstance.value.setOption(theOption, true)
    chartInstance.value.on('click', handleChartClick)
  }
})
watch(
  () => props.barData.gdp_1st,
  () => {
    theOption.series[0].data[0].value = props.barData.gdp_1st
    theOption.series[0].data[1].value = props.barData.gdp_2nd
    theOption.series[0].data[2].value = props.barData.gdp_3rd
    chartInstance.value.setOption(theOption, true)
  },
  { deep: true }
)
window.addEventListener('resize', () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
})
</script>

<style lang="scss" scoped>
.echarts_container {
  width: 100vw;
  height: 100vh;
}
</style>
